using FytSoa.Application.Erp.Param;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using FytSoa.Domain.Hr;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp_流程管理服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpFlowService : IApplicationService 
{
    private readonly SugarRepository<ErpFlow> _thisRepository;
    private readonly SugarRepository<HrEmployee> _employeeRepository;
    public ErpFlowService(SugarRepository<ErpFlow> thisRepository
    ,SugarRepository<HrEmployee> employeeRepository)
    {
        _thisRepository = thisRepository;
        _employeeRepository = employeeRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpFlowDto>> GetPagesAsync(ErpFlowSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Name.Contains(param.Key))
            .WhereIF(!string.IsNullOrEmpty(param.FlowType),m=>m.FlowType==param.FlowType)
            .WhereIF(param.Status=="1",m=>m.Status)
            .WhereIF(param.Type==1,m=>m.IsApply)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        var result=query.Adapt<PageResult<ErpFlowDto>>();
        /*if (result.Items.Count == 0) return result;
        {
            var userIds = (from item in result.Items from row in item.Nodes select row.EmployeeId).ToList();
            userIds = userIds.GroupBy(m => m).Select(m => m.Key).ToList();
            var userList = await _employeeRepository.AsQueryable()
                .Where(m => userIds.Contains(m.Id))
                .Includes(m=>m.OrganizationObj)
                .ToListAsync();
            foreach (var item in result.Items)
            {
                foreach (var row in item.Nodes)
                {
                    var user = userList.FirstOrDefault(m => m.Id == row.EmployeeId);
                    if(user==null) continue;
                    row.Name = user.Name;
                    row.Org = user.OrganizationObj.Name;
                }
            }
        }*/
        return result;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpFlowDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        var result=model.Adapt<ErpFlowDto>();
        var userIds = result.Nodes.Select(m => m.EmployeeId);
        var userList = await _employeeRepository.AsQueryable()
            .Where(m => userIds.Contains(m.Id))
            .Includes(m=>m.OrganizationObj)
            .ToListAsync();
        foreach (var item in result.Nodes)
        {
            var user = userList.FirstOrDefault(m => m.Id == item.EmployeeId);
            if(user==null) continue;
            item.Name = user.Name;
            item.Org = user.OrganizationObj.Name;
        }
        return result;
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task AddAsync(ErpFlowDto model)
    {
        var toDay = await _thisRepository.CountAsync(m=>m.CreateTime.ToString("yyyy-MM")==DateTime.Now.ToString("yyyy-MM"));
        model.Number = "FL".ResNumber(toDay, "yyyyMM");
        var index = 0;
        foreach (var item in model.Nodes)
        {
            index += 1;
            item.Number = index;
        }
        await _thisRepository.InsertAsync(model.Adapt<ErpFlow>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task ModifyAsync(ErpFlowDto model)
    {
        await _thisRepository.UpdateAsync(model.Adapt<ErpFlow>());
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
